<template>
  <el-card class="box-card" style="margin:12px 10px 0">
    <!-- 面包屑 -->
    <div slot="header" class="clearfix" v-if="isShow">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{subjectName}}</el-breadcrumb-item>
        <el-breadcrumb-item>目录管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="header">
      <!-- 头部表单筛选区域start -->
      <el-form label-width="80px" class="elform" size="small">
        <el-form-item label="目录名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="状态">
        <el-select v-model="form.status" placeholder="请选择" >
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        </el-form-item>
        <el-button class="btn" style="margin-left:10px" @click="hClear">清除</el-button>
        <el-button class="btn" type="primary" @click="hSearch">搜索</el-button>
      </el-form>
      <!-- 头部表单筛选区域end -->
      <!-- 头部新增目录区域start -->
      <div class="add">
        <el-button  type="text" @click="$router.push('list')" v-show="isShow"><i class="el-icon-back"></i>返回学科</el-button>
        <el-button type="success" icon="el-icon-edit"  @click="hOpenDialog">新增目录</el-button>
      </div>
      <!-- -----------------------添加弹出层-------------------------- -->
      <el-dialog
        title="新增目录"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <el-form ref="addForm" :model="addform" :rules="rules" label-width="80px">
          <el-form-item label="所属学科" v-if="!isShow">
            <el-select clearable v-model="addform.subjectID" placeholder="请选择" style="width:263px">
              <el-option v-for="item in subjectDate" :key="item.value" :label="item.label" :value="item.value" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录名称"  prop="directoryName">
            <el-input v-model="addform.directoryName"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" >
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="hAdd">确 定</el-button>
        </span>
      </el-dialog>
    <!-- -----------------------修改目录弹出层---------------------------->
    <el-dialog
        title="修改目录"
        :visible.sync="dialogVisibleUpdate"
        width="30%"
        :before-close="handleClose">
        <el-form label-width="80px" ref="updateForm" :model="updateform" :rules="rules" >
          <el-form-item label="所属学科" v-if="!isShow">
            <el-select clearable v-model="updateform.subjectID" placeholder="请选择" style="width:263px">
              <el-option v-for="item in subjectDate" :key="item.value" :label="item.label" :value="item.value" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录名称"  prop="directoryName">
            <el-input v-model="updateform.directoryName"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" >
          <el-button @click="dialogVisibleUpdate = false">取 消</el-button>
          <el-button type="primary" @click="doUpdate">确 定</el-button>
        </span>
      </el-dialog>
    <!-- 头部新增目录区域end -->
    </div>
    <div class="center"><i class="el-icon-info"></i> 数据一共{{totalCount}}条</div>
    <!-- 表格数据部分start -->
     <el-table
      :data="tableData"
      style="width: 100%; " class="elTable">
        <el-table-column
          label="序号"
          type="index"
          :index="indexMethod"
          width="100">
        </el-table-column>
        <el-table-column
          prop="subjectName"
          label="所属学科"
          width="100">
        </el-table-column>
        <el-table-column
          prop="directoryName"
          label="目录名称"
          width="100">
        </el-table-column>
        <el-table-column
          prop="username"
          label="创建者">
        </el-table-column>
        <el-table-column
          label="创建日期" width="160">
          <template slot-scope="scope">
            {{scope.row.addDate | fFormateDate}}
          </template>
        </el-table-column>
        <el-table-column
          prop="totals"
          label="面试题数量">
        </el-table-column>
        <el-table-column
        label="状态">
        <template slot-scope="scope">
          <!-- {{scope.row.comment_status}} -->
          <span v-if="scope.row.state === 1">已启用</span>
          <span v-else-if="scope.row.state === 0" type="danger">已禁用</span>
        </template>
        </el-table-column>
        <el-table-column
        label="操作">
        <template slot-scope="scope">
          <!-- @click="hToggle" -->
          <el-button  type="text" @click="hToggle(scope.$index, scope.row)">{{scope.row.state ? "禁用" : "启用" }}</el-button>
          <el-button type="text" :disabled="scope.row.state ? true : false "  @click="hUpdate(scope.$index, scope.row)">修改</el-button>
          <el-button type="text" :disabled="scope.row.state ? true : false "  @click="hDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格数据部分end -->
    <!-- 分页部分start -->
    <div class="footer">
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="hCurrentChange"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="10"
      layout="prev, pager, next, sizes, jumper"
      :current-page="curpage"
      :total="totalCount">
    </el-pagination>
  </div>
    <!-- 分页部分end -->
  </el-card>
</template>

<script>
import { list, remove, add, update, changeState } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects'
// import { simple } from '@/api/hmmm/subjects'
export default {
  name: 'directorys',
  data () {
    return {
      isShow: false, // 判断面包屑导航是否显示
      dialogVisible: false, // 弹出框默认关闭状态
      dialogVisibleUpdate: false, // 弹出框默认关闭状态
      totalCount: 100, // 总页数
      curpage: 1, // 当前页
      pageSize: 10,
      form: {
        name: null, // 筛选的目录名称默认null
        status: null // 筛选的状态默认null
      },
      addform: { // 默认的新增学科和目录名称为null
        subjectID: null,
        directoryName: null
      },
      updateform: { // 默认的新增学科和目录名称为null
        id: null,
        subjectID: null,
        subjectName: null,
        directoryName: null
      },
      subjectDate: [], // 用来渲染学科分类的数据
      tableData: [], // 表格部分的初始数据
      subjectName: '', // 路由跳转后的subjectName
      id: null, // 所属学科的id

      rules: { // 表单的验证规则
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      }
    }
  },
  filters: {
    fFormateDate: function (val) {
      const dt = new Date(val)
      return dt.getFullYear() + '-' + dt.getMonth() + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
    }
  },
  watch: {
    // 监听地址栏路由的变化
    $route (val) {
      this.id = val.query.id || null
      this.loadDirectorys()
    }
  },
  created () {
    this.loadDirectorys()
  },
  methods: {
    indexMethod (index) {
      const curpage = this.curpage // 当前页码
      const limitpage = this.pageSize // 每页条数
      return (index + 1) + (curpage - 1) * limitpage
    },
    // ---------页面一打开就加载目录----------------
    async loadDirectorys () {
      this.isShow = false
      // 1.先判断是否有动态路由
      if (this.$route.query.id) {
        // 1.1将面包屑和返回按钮呈现出来
        this.isShow = true
        this.subjectName = this.$route.query.name
        this.id = this.$route.query.id
        this.addform.subjectID = Number(this.$route.query.id)
      }
      const res = await list({
        subjectID: this.id,
        page: this.curpage,
        pagesize: this.pageSize,
        directoryName: this.form.name,
        state: this.form.status
      })
      console.log('获取目录', res)
      // console.log('1', this.form.status, '2', this.form.name)
      // 2.获取的数据赋值给tableData
      this.tableData = res.data.items
      // 3.更新总页数
      this.totalCount = res.data.counts
    },
    // ---------点击实现清除------------------
    hClear () {
      // 对表单进行重置
      this.form.name = ''
      this.form.status = ''
    },
    // ----------点击搜索按钮实现搜索功能-----------
    async hSearch () {
      // 1.回到第一页进行查询
      this.curpage = 1
      // 2.根据条件重新渲染页面
      this.loadDirectorys()
    },
    // ----------点击删除实现删除功能---------------
    hDelete (index, row) {
      // console.log(index, row)
      // 1.发送请求
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await remove({
            id: row.id
          })
          console.log(res)
          // 2.成功消息提示
          this.$message.success('删除成功')
          // 3.重新渲染页面
          this.loadDirectorys()
        } catch (err) {
          this.$message.error('删除失败')
        }
      }).catch(() => {
      })
    },
    // ------------打开弹出层------------
    async hOpenDialog () {
      // 1.打开弹出层
      this.dialogVisible = true
      // 2.发送请求获取数据
      const res = await simple()
      console.log('学科名称列表', res)
      this.subjectDate = res.data
      console.log('学科名称列表', this.subjectDate)
    },
    // ----------实现添加功能---------------
    async hAdd () {
      // 先进行表单验证
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          try {
            // 1.发送请求
            const res = await add({
              subjectID: this.addform.subjectID,
              directoryName: this.addform.directoryName
            })
            // console.log(this.addform.subjectID)
            console.log(res)
            // 2.成功消息提示
            this.$message.success('添加目录成功')
            // 3.清空表单
            this.addform.subjectID = ''
            this.addform.directoryName = ''
            // 4..关闭弹出层
            this.dialogVisible = false
            // 5.重新渲染页面
            this.loadDirectorys()
          } catch (err) {
            this.$message.error('添加目录失败')
          }
        }
      })
    },
    async hUpdate (index, row) {
      // console.log(index, row)
      // 1.打开弹出层
      this.dialogVisibleUpdate = true
      // 2.发送请求获取数据
      const res = await simple()
      console.log('学科名称列表', res)
      this.subjectDate = res.data
      console.log('学科名称列表11111', this.subjectDate)
      // 3.实现数据回填
      this.updateform.subjectID = row.subjectID
      this.updateform.subjectName = row.subjectName
      this.updateform.directoryName = row.directoryName
      this.updateform.id = row.id
    },
    async doUpdate () {
      this.$refs.updateForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await update({
              id: this.updateform.id,
              subjectID: this.updateform.subjectID,
              directoryName: this.updateform.directoryName
            })
            console.log(res)
            // 2.成功消息提示
            this.$message.success('修改目录成功')
            // 3.关闭弹出层
            this.dialogVisibleUpdate = false
            // 4.重新渲染页面
            this.loadDirectorys()
          } catch (err) {
            this.$message.error('修改目录失败')
          }
        }
      })
    },
    // -----------点击启用禁用按钮-------------
    async hToggle (index, row) {
      // console.log(index, row)
      try {
        if (row.state === 0) {
          row.state = 1
        } else if (row.state === 1) {
          row.state = 0
        }
        const res = await changeState({
          id: row.id,
          state: row.state
        })
        this.isDisabled = !this.isDisabled
        this.$message.success('操作成功')
        console.log('变更状态', row.state, res)
        // this.loadDirectorys()
        // if (row.state === 0) {
        //   row.state = 1
        // } else if (row.state === 1) {
        //   row.state = 0
        // }
        // this.loadDirectorys()
      } catch (err) {
        this.$message.error('操作失败')
      }
    },
    // ------------点击切换页面----------------
    handleSizeChange (val) {
      // console.log(`当前的 ${val}`)
      // 1.更新pageSize的
      this.pageSize = val
      // // 2.回到第一页查询
      // this.curpage = 1
      // 3.重新渲染页面
      this.hCurrentChange(1)
    },
    hCurrentChange (val) {
      // 1.更新当前页
      this.curpage = val
      // 2.重新渲染页面
      this.loadDirectorys()
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    }
  }
}
</script>

<style scoped>
.header {
display: flex;
flex-direction: row;
justify-content:space-between
}
.elform {
width: 65%;
display: flex;
flex-direction: row;
justify-content:space-between
}
.btn {
  display: inline-block;
  height: 35px;
}
.center {
  height: 35px;
  line-height: 35px;
  font-size: 14px;
  color: grey;
  background-color:rgba(244, 244, 245);
  padding-left: 20px;
  border-radius: 5px;
  margin-bottom: 10px;
}
.footer {
  float: right;
  margin: 15px 0;
}
</style>
